// miniprogram/pages/More/index.js

import {
  getPlayerQR,
  getplayer_pics,
  deletefile
} from '../../http/game';

import {
  uploadUserInfoImagealioss
} from '../../utils/upload';


const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    userInfo: undefined, //用户信息
    date: '',
    city: '',
    islogin: false,
    autologin: undefined,
    autoreg: undefined,
    isopenopenplayerbasicinfo: true,
    password: '',
    isfoucs: false,
    iscanopenredpackage: false,
    registerstatus: "",
    playerinfo: {},
    page: 1,
    totalpage: '',
    thurmbs: [],
    isdelete:false,
    ishowinfo:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getStorageSync('autoreg') == '1') {
      this.setData({
        autoreg: true
      })
    } else {
      this.setData({
        autoreg: false
      })
    }
    if (wx.getStorageSync('autologin') == '1') {
      this.setData({
        autologin: true
      })
    } else {
      this.setData({
        autologin: false
      })
    }






  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.popup = this.selectComponent("#popup");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4
      })
    };

    console.log(app.globalData.userInfo);
    if (app.globalData.userInfo.openid && app.globalData.userInfo.session_key) {

      console.log(app.globalData.userInfo);
      this.setData({
        islogin: true
      })
    }

    if (!this.data.islogin && wx.getStorageSync('autoreg') == "1") {
      var that = this;
      app.wxlogin(app, function () {

        that.setData({
          islogin: true
        });
        that.onShow();
      });
      return;
    }

    if (!this.data.islogin) {
      this.login();
      return;
    }

    var userInfo = app.globalData.userInfo;
    if (userInfo != undefined && userInfo != null) {
      this.setData({
        userInfo: userInfo
      });
      // var obj = this.selectComponent("#register");
      // obj.filldata(userInfo.data);
    }
    this.getdata();
    var page = this.data.page == 1 ? this.data.page : this.data.page - 1;
    this.setData({
      page
    });
    this.getplayer_pics();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },


  getplayer_pics: function () {
    let {
      userInfo,
      thurmbs,
      page,
      totalpage
    } = this.data;
    if (userInfo.player_id) {
      getplayer_pics({
        player_id: userInfo.player_id,
        page
      }).then(res => {
        console.log(res);
        if (res.errorcode.code == 'ok') {
          if (res.data && res.data.list && res.data.list.length > 0) {
            thurmbs = res.data.list;
            page = page;
            totalpage = parseInt(res.data.pagenumtotal);
            this.setData({
              thurmbs,
              page,
              totalpage
            });
          }
        }
      });
    }
  },

  deletop:function() {
  
        this.setData({isdelete:!this.data.isdelete});
      
      
  },

  deletepic:function (e) {
      var file_id = e.detail;
      let {userInfo} = this.data;
      console.log(e);
      var that = this;
      wx.showModal({
        title: '是否删除',
        cancelText:'再想想',
        confirmText:'确认',
        success:function(res) {
            
            if(res.confirm){
              deletefile({file_id,player_id:userInfo.player_id}).then(res=>{
                if(res.errorcode.code =='ok'){
                  wx.showToast({
                    title: '删除成功',
                    icon:'success',
                  })
                  that.getplayer_pics();
                }
              });
            }
        }
      })
    
  },

  getdata() {
    var that = this;
    app.getregsiterstatus(that.data.userInfo.player_id, function (res) {
      that.setData({
        registerstatus: res.data.data,
      })
    }, function () {

    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  onResize: function (res) {
    //this.onShow();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 

  changepage:function(e) {
      const {page} = e.currentTarget.dataset;
      this.setData({page:page});
      this.getplayer_pics();
  },

  swautologin: function (e) {
    if (e.detail.value) {
      wx.setStorageSync('autologin', '1');
      // this.login();
    } else {
      wx.setStorageSync('autologin', '0');
    }
  },
  swautoreg: function (e) {
    if (e.detail.value) {
      wx.setStorageSync('autoreg', '1');

    } else {
      wx.setStorageSync('autoreg', '0');
    }
  },

  login: function () {

    if (!app.checkislogin()) {
      wx.showModal({
        title: '请先登陆才能查看个人中心的内容',
        confirmText: "确定",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            console.log(res);
            wx.navigateTo({
              url: '../login/login',
            })

            return;
          } else {
            wx.switchTab({
              url: '../index/index',
            })
            return;
          }

        }
      })
    }


  },


  openmenu: function (e) {
    var index = e.currentTarget.dataset.index;
    if (index == 0) {
      wx.navigateTo({
        url: '',
      })
    } else if (index == 1) {
      wx.navigateTo({
        url: './information/information',
      })
    } else if (index == 2) {
      wx.navigateTo({
        url: './score/score',
      })
    } else if (index == 3) {
      wx.navigateTo({
        url: './setting/setting',
      })
    } else if (index == 4) {
       var that = this;
      wx.showModal({
        cancelColor: 'cancelColor',
        title:'是否退出？',
        cancelText:'再想想',
        confirmText:'退出',
        success:function(res) {
            if(res.confirm){
              app.logout();
              that.setData({
                islogin: false
              });
              wx.setStorageSync('autoreg', '0');
              wx.setStorageSync('userInfo', '');
              that.onShow();
            }
        }
      })
      
    } else if (index == 5) {
      wx.navigateTo({
        url: './registerlists/registerlists',
      })
    } else if (index == 6) {
      wx.navigateTo({
        url: '../Personal_matches/mypersonalmatch/mypersonalmatch',
      })
    } else if (index == 7) {
      wx.navigateTo({
        url: '../Personal_matches/history/history?type=1&ismy=1',
      })
    }
    else if (index == 10) {
      wx.navigateTo({
        url: '/pages/speactor/ticket/ticketlist/index',
      })
    }
  },
  showPopup() {
    this.popup.showPopup();
  },
  //二维码取消事件
  _error() {
    this.popup.hidePopup();
  },

  _success:function(){
    this.popup.hidePopup();
  },

  openQrcode: async function () {

    const {
      userInfo
    } = this.data;
    let {
      playerinfo
    } = this.data;
    const res = await getPlayerQR({
      type: 3,
      pl_id: userInfo.player_id
    }) // 30775
    //console.log(res);
    playerinfo.pl_cn_name = userInfo.trueName;
    this.setData({
      playerinfo,
      QrcodeUrl: res,
    });
    this.showPopup();
  },


  inputpassword(e) {
    var password = e.detail.value;
    this.setData({
      password: password,
    });
  },
  testwechatpar() {
    var password = this.data.password;
    if (!password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      this.setData({
        isfoucs: true,
      })
      return;
    }

    if (password != '861115') {
      wx.showToast({
        title: '密码不正确',
        icon: 'none'
      })
      this.setData({
        isfoucs: true,
      })
      return;
    }
    var that = this;
    var date = new Date();
    var orderno = "phpminiapp" + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + Math.floor(Math.random() * 100);
    console.log(orderno);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.interfacewechatpaycompanytoperson,
      data: {
        openid: app.globalData.openid,
        re_user_name: '伍俊杰',
        amount: 30,
        partner_trade_no: orderno,
        desc: "企业付款0.3月报销"
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success(res) {
        console.log(res);
        if (res.data.indexOf("ok") >= 0) {

          wx.showToast({
            title: '支付成功',
            icon: "none",
          })
          that.setData({
            password: '',
          });
        } else {
          wx.showToast({
            title: '支付失败',
            icon: "none",
          })
        }


      },
      fail(res) {
        wx.showToas({
          title: res.data.msg,
          icon: 'none'
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  testwechathongbao() {

    if (!this.data.iscanopenredpackage) {
      wx.showToast({
        title: '微信红包领取场景不对',
        icon: "none",
      })
      return;
    }

    var password = this.data.password;
    if (!password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      this.setData({
        isfoucs: true,
      })
      return;
    }

    if (password != '1111') {
      wx.showToast({
        title: '密码不正确',
        icon: 'none'
      })
      this.setData({
        isfoucs: true,
      })
      return;
    }
    var that = this;
    var date = new Date();
    var orderno = "phpminiapp" + date.getFullYear() + (date.getMonth() + 1) + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + Math.floor(Math.random() * 100);

    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.interfacewechathongbao,
      data: {
        openid: app.globalData.openid,
        re_user_name: '伍俊杰',
        orderno: orderno,
        amount: 30,
        desc: "随机微信红包"
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success(res) {
        console.log(res);

        if (res.data == 2) {

          wx.showToas({
            title: '红包发送失败',
            icon: "none",
          })
          return

        }

        if (res.data.code == 1) {
          wx.sendBizRedPacket({

            timeStamp: res.data.timeStamp, // 支付签名时间戳，

            nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位

            package: res.data.package, //扩展字段，由商户传入

            signType: res.data.signType, // 签名方式，

            paySign: res.data.paySign, // 支付签名

            success: function (res) {

              wx.showToas({
                title: '红包发送成功',
                icon: "none",
              })
              console.log(res);
              that.setData({
                password: '',
              });
            },

            fail: function (res) {

              console.log(res)

            },

            complete: function (res) {

              console.log(res)

            }
          });
        }


      },
      fail(res) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      },
      complete() {
        wx.hideLoading()
      }
    })
  },

  openscan() {
    wx.scanCode({
      success: (res) => {
        console.log("扫码结果");
        console.log(res);

      },
      fail: (res) => {
        console.log(res);
      }
    })
  },



  //打开个人信息的页面
  openplayerbasicinfo: function () {
    this.setData({


      isopenopenplayerbasicinfo: !this.data.isopenopenplayerbasicinfo
    })
  },

  openliveroom: function () {
    if (!this.data.islogin) {

      wx.showModal({
        title: '请先使用微信登陆',
        cancelColor: 'cancelColor',
      })
      return;
    }
    wx.navigateTo({
      url: '../liveroom/index',
    })
  },
  changebanduserlists: function (e) {

    var userInfo = this.data.userInfo;
    var banduserlists = userInfo.banduserlists;
    var value = e.detail.value;

    console.log("changebanduserlistsfunction");
    console.log(e);
    var that = this;
    app.globalData.userInfo.trueName = banduserlists[value].truename;
    app.globalData.userInfo.openid = banduserlists[value].openid;
    app.globalData.userInfo.userID = banduserlists[value].userid;
    app.globalData.userInfo.player_id = banduserlists[value].player_id;
    app.globalData.userInfo.cardnumber = banduserlists[value].cardnumber;
    console.log(app.globalData.userInfo);

    app.getplayerpic(app.globalData.userInfo.userID, app.globalData.userInfo.player_id, function (res) {
      console.log(res);
      if (res.data.data) {
        app.globalData.userInfo.pl_photo = res.data.data.pl_photo;
        app.globalData.userInfo.avatarUrl = res.data.data.avatarUrl;
        console.log(app.globalData.userInfo);
        that.setData({
          userInfo: app.globalData.userInfo
        });
        var isautologin = wx.getStorageSync("isautologin");
        if (isautologin) {
          wx.setStorageSync('userInfo', app.globalData.userInfo);
        }
        that.getdata();
      }
    })


  },
  async onChooseAvatar(e){
    console.log(e.detail.avatarUrl);
    var that = this;
    if(e.detail.avatarUrl){
      // 先保存临时文件到本地
      const fs = wx.getFileSystemManager();
      const savedFilePath = `${wx.env.USER_DATA_PATH}/temp_avatar_${Date.now()}.jpg`;
      
      fs.saveFile({
        tempFilePath: e.detail.avatarUrl,
        filePath: savedFilePath,
        success: function(saveRes) {
          console.log('文件保存成功:', saveRes);
          // 使用保存后的文件路径上传
          uploadUserInfoImagealioss(saveRes.savedFilePath, function(res){
            if(res){
              console.log(res);
              wx.showToast({
                title: '更新成功',
              })
              app.globalData.userInfo.avatarUrl = res;
              var isautologin = wx.getStorageSync("isautologin");
              if (isautologin) {
                wx.setStorageSync('userInfo', app.globalData.userInfo);
              }
              that.onShow();
              
              // 清理临时文件
              fs.unlink({
                filePath: saveRes.savedFilePath,
                complete: function() {
                  console.log('临时文件已清理');
                }
              });
            }
          });
        },
        fail: function(error) {
          console.error('文件保存失败:', error);
          wx.showToast({
            title: '头像处理失败，请重试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }
  },
  
  changeshowinfo:function(){
    this.setData({ishowinfo:!this.data.ishowinfo});
  },

  async onupdatenickname(e){
    console.log(e);
    var that = this;
    if(e.detail.value){
      var nickname = e.detail.value;
        console.log(nickname);
          //return ;
           app.updateUserinfo({nickname:nickname}, function(res){
            if(res){
              wx.showToast({
                title: '更新成功',
              })
              app.globalData.userInfo.nickName = nickname;
              var isautologin = wx.getStorageSync("isautologin");
              if (isautologin) {
                wx.setStorageSync('userInfo', app.globalData.userInfo);
              }
              that.onShow();
            }
        });
 
}
  },
})
